/*
 * Unidata Platform Community Edition
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 * This file is part of the Unidata Platform Community Edition software.
 *
 * Unidata Platform Community Edition is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Unidata Platform Community Edition is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
package org.unidata.mdm.meta.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidata.mdm.core.configuration.UserMessageConstants;
import org.unidata.mdm.core.context.UpsertUserEventRequestContext;
import org.unidata.mdm.core.service.SecurityService;
import org.unidata.mdm.core.service.UserService;
import org.unidata.mdm.core.util.SecurityUtils;
import org.unidata.mdm.meta.service.MetaModelImportService;
import org.unidata.mdm.meta.type.input.meta.MetaGraph;
import org.unidata.mdm.system.util.TextUtils;

import com.hazelcast.topic.Message;
import com.hazelcast.topic.MessageListener;


/**
 * The listener interface for receiving metaIE events. The class that is
 * interested in processing a metaIE event implements this interface, and the
 * object created with that class is registered with a component using the
 * component's <code>addMetaIEListener<code> method. When the metaIE event
 * occurs, that object's appropriate method is invoked.
 */
public class MetaImportListener implements MessageListener<MetaGraph> {

	/** The meta IE service. */
	private MetaModelImportService metaModelImportService;

	/** The local member UUID. */
	private String localMemberUUID;

	/** The security service. */
	private SecurityService securityService;

	/** The user service. */
	private UserService userService;

    /** The logger. */
    private static Logger LOGGER = LoggerFactory.getLogger(MetaImportListener.class);

	/**
	 * Instantiates a new meta IE listener.
	 *
	 * @param metaModelImportService            the meta IE service
	 * @param securityService            security service
	 * @param userService the user service
	 * @param localMemberUUID            the local member UUID
	 */
	public MetaImportListener(MetaModelImportService metaModelImportService, SecurityService securityService, UserService userService, String localMemberUUID) {
		this.metaModelImportService = metaModelImportService;
		this.localMemberUUID = localMemberUUID;
		this.securityService = securityService;
		this.userService = userService;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.hazelcast.core.MessageListener#onMessage(com.hazelcast.core.Message)
	 */
	@Override
	public void onMessage(Message<MetaGraph> message) {
		if (message.getPublishingMember().getUuid().equals(localMemberUUID)) {
			return;
		}

		this.securityService.authenticate(message.getMessageObject().getSecurityToken(), true);
		try {
			// TODO: 13.05.2020 CHECK THIS AT NODES
			this.metaModelImportService.apply(message.getMessageObject());
		} catch (Exception e) {
	        try {
	            UpsertUserEventRequestContext uueCtx = UpsertUserEventRequestContext.builder()
	                    .login(SecurityUtils.getCurrentUserName())
	                    .type("META_FULL_IMPORT")
	                    .content(TextUtils.getText(
	                            UserMessageConstants.DATA_IMPORT_METADATA_FAILED))
	                    .details(e.getMessage())
	                    .build();
	            this.userService.upsert(uueCtx);
	        } catch (Exception e1) {
	            LOGGER.error("Cannot create report due to an exception", e1);
	        }
		}

	}

}
